# src/macro.py

from dataclasses import dataclass


macro_head = """
set echo

@@ Thermo-Calc-Macro-file.TCM, last edited on 20251012.
@@ Each line must be less than 80 columns!!!
@@ It needs to set elements in <def_elem>,
@@                 phases in <restore phases>,
@@                 temperature in <set_cond>,
"""


macro_tail = """
s_c t=1873
c_e
l_e SCREEN AWNS

s_c t=1573
c_e
l_e SCREEN AWNS

s_c t=1273
c_e
l_e SCREEN AWNS

s_c t=973
c_e
l_e SCREEN AWNS

s_c t=673
c_e
l_e SCREEN AWNS

s_c t=373
c_e
l_e SCREEN AWNS

s_c t=73
c_e
l_e SCREEN AWNS


@@ Plot module ================================================================

set_a_v 1 t 73 1873 1
step N
post
s_l_c d
s_d_a x t

s_d_a y G *
dump PNG M G-T.png Y
m_e_d G-T.exp

s_d_a y G(*) *
dump PNG M GI-T.png Y
m_e_d GI-T.exp

s_d_a y H *
dump PNG M H-T.png Y
m_e_d H-T.exp

s_d_a y H(*) *
dump PNG M HI-T.png Y
m_e_d HI-T.exp

s_d_a y S
dump PNG M S-T.png Y
m_e_d S-T.exp

s_d_a y S(*) *
dump PNG M SI-T.png Y
m_e_d SI-T.exp

s_d_a y np(*) *
dump PNG M NP-T.png Y
m_e_d NP-T.exp

s_d_a y x(*,*) *
dump PNG M X-T.png Y
m_e_d X-T.exp

s_d_a y y(*,*) *
dump PNG M Y-T.png Y
m_e_d Y-T.exp


@@ End module =================================================================
"""


@dataclass
class AlloySystem:
    phases: list[str]
    comps: list[str]
    fracts: list[float]


def generate_macro(tdb_file: str, alloy_system: AlloySystem) -> str:
    phases = alloy_system.phases
    comps = alloy_system.comps
    fracts = alloy_system.fracts

    macro_body = f"""
@@ Input module ===============================================================
goto    data
switch  user {tdb_file}

def_elem {' '.join(comps)}

reject  phases /all
restore phases {' '.join(phases)}

get_data


@@ Calcutate module ===========================================================
goto    poly_3

s_c n=1 p=101325
"""
    comp_fracts = [f"s_c x({e})={c:.6f}" for e, c in zip(comps, fracts)]
    macro_comps = "\n".join(comp_fracts[1:])  # Keep one degree of freedom

    return macro_head + macro_body + macro_comps + macro_tail